// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import StartUp from "../../../lib/StartUp";
import CM from "../../../lib/cache/CM";
import { monitor, selfCls } from "../../../lib/common/Decorator";
import { Manager } from "../../../lib/common/Manager";
import DField from "../../cache/DField";
import ToolExt from "../../common/ToolExt";
import GOMachine, { MachineArgs } from "../machine/GOMachine";



const {ccclass, property} = cc._decorator;

@selfCls
export default class MachineManager extends Manager {
    private _dict:Map<number, GOMachine> = new Map();
    get parentRoot(): cc.Node {
        return StartUp.instance.gameRoot;
    }

    public async do(): Promise<void> {
        return new Promise<void>((resolve, reject)=>{
            resolve();
        })
    }

    createMachine(args:MachineArgs) {
        let go = new cc.Node();
        let machine = go.addComponent(GOMachine);
        this.node.addChild(go);
        machine.init(args);
        let maxCol = CM.ins(CM).get(DField).col;
        let index = ToolExt.rowColToIndex(args.row, args.col, maxCol);
        this._dict.set(index, machine);
    }

    @monitor("DField/content")
    on_content_change(attrName, oldVal, newVal) {
        let arr = attrName.split("/");
        if (arr.length > 1) {//修改了数组里面的值
            let index = Number(arr[arr.length-1]);
            if (this._dict.has(index)) {//有机关了 删除旧的机关换成新的？
                let machine = this._dict.get(index);
                machine.node.destroy();
            } else {//创建机关在这边
                let maxCol = CM.ins(CM).get(DField).col;
                let row = ToolExt.indexToRow(index, maxCol);
                let col = ToolExt.indexToCol(index, maxCol);
                this.createMachine({row:row, col:col, id:newVal})
            }
        }
    }
}
